package com.ultrapower.config;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ultrapower.util.StringUtil;

/**
 * 
 * @author wangy
 *
 */
public class Config {
	private static Logger logger = LoggerFactory.getLogger(Config.class);
	private static Properties CONFIG = new Properties();
	static {
		InputStream is = Config.class.getClassLoader().getResourceAsStream("config.properties");
		try {
			CONFIG.load(is);
		} catch (IOException e) {
			logger.error("load error", e);
		}
	}

	/**
	 * 
	 * @param key
	 * @param defaultValue
	 * @return
	 */
	public static String getString(String key, String defaultValue) {
		return CONFIG.getProperty(key, defaultValue);
	}

	/**
	 * 
	 * @param key
	 * @param defaultValue
	 * @return
	 */
	public static int getInt(String key, int defaultValue) {
		String val = CONFIG.getProperty(key);
		if (StringUtil.isEmpty(val)) {
			return defaultValue;
		} else {
			return Integer.parseInt(val);
		}
	}
	/**
	 * 
	 * @param configMappings
	 * @return
	 */
	public static Properties getPropertiesByMapping(Set<ConfigMapping<?>> configMappings) {
		Properties result = new Properties();
		configMappings.forEach(cm -> {
			if (StringUtil.isEmpty(cm.getBeanConfig())) {
				result.setProperty(cm.getFileConfig(), CONFIG.getProperty(cm.getFileConfig(), cm.getDefaultConfig()+""));
			}else{
				result.setProperty(cm.getBeanConfig(), CONFIG.getProperty(cm.getFileConfig(), cm.getDefaultConfig()+""));
			}
		});
		return result;
	}
}
